<template>
  <div class="client-manager">
    <div class="flex-column client-info" v-loading="isLoading">
      <template v-if="isQueryDetailPermission">
        <div class="client-info-tabs">
          <el-tabs v-model="activeTabPaneName" @tab-change="getRectificationCount">
            <el-tab-pane label="客户信息" :name="clientType.CLIENT_INFO"></el-tab-pane>
            <el-tab-pane label="服务团队" :name="clientType.CLIENT_SERVICE"></el-tab-pane>
            <el-tab-pane label="营销阶段" :name="clientType.CLIENT_STAGE"></el-tab-pane>
            <el-tab-pane label="施工日志" :name="clientType.CONSTRUCTION_LOG"></el-tab-pane>
            <el-tab-pane label="施工计划" :name="clientType.CONSTRUCTION_PLAN"></el-tab-pane>
            <el-tab-pane label="发包信息" :name="clientType.Package_Information"></el-tab-pane>
            <el-tab-pane label="验收计划" :name="clientType.ACCEPTANCE_PLAN"></el-tab-pane>
            <el-tab-pane :name="clientType.RECTIFICATION">
              <template #label>
                <div style="color: #ff3333">
                  售后清单
                  <span v-show="rectificationNum">({{ rectificationNum }})</span>
                </div>
              </template>
            </el-tab-pane>
            <el-tab-pane label="附件" :name="clientType.ATTACHMENT"></el-tab-pane>
            <el-tab-pane label="收款计划" :name="clientType.PAYMENT_PLAN"></el-tab-pane>
            <el-tab-pane label="合同资料" :name="clientType.Contract_Materials"></el-tab-pane>
          </el-tabs>
          <div class="button-container">
            <el-button class="submit-task" type="primary" style="margin-left: auto" @click="openSubmitTask">发起任务 </el-button>
            <el-button class="back-page" @click="handelBack">返回上一页</el-button>
          </div>
        </div>
        <component :is="cmpInstance" :customerId="customerId" @set-active="setActive"></component>
      </template>
      <el-empty v-else description="抱歉，您无查看权限">
        <template #default>
          <el-button type="primary" @click="handelBack">返回上一页</el-button>
        </template>
      </el-empty>
    </div>

    <!--  发起任务 start -->
    <div class="submit-task-dialog">
      <el-dialog
        v-model="isShowSubmitTask"
        width="600"
        :align-center="true"
        :show-close="false"
        :close-on-click-modal="false"
        @close="handelSubmitTaskClose"
      >
        <template #header>
          <title-view title="发起任务"></title-view>
        </template>
        <el-form
          style="margin: 50px 0"
          v-if="isShowSubmitTask"
          ref="submitTaskFormRef"
          :model="submitTaskForm"
          :rules="submitTaskRules"
          status-icon
        >
          <el-form-item label="任务模板" prop="packageId">
            <el-select popper-class="select-user-popper" v-model="submitTaskForm.packageId" placeholder="请选择" clearable>
              <template #header>
                <div class="content-item-search">
                  <el-input placeholder="请输入关键词" v-model="templateKeyword" @change="handelSearchTemplate" />
                  <svg-icon iconClass="searchBox-icon" style="font-size: 24px" @click="handelSearchTemplate" />
                </div>
              </template>
              <el-option
                v-for="templateItem in templateList"
                :key="templateItem.packageId"
                :v-loading="selectTemplateLoading"
                :label="templateItem.packageName"
                :value="templateItem.packageId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button style="width: 92px; background-color: #f2f3f5" @click="handelSubmitTaskClose" size="default"
              >取消
            </el-button>
            <el-button style="width: 92px" type="primary" @click="handelSubmitTask" size="default">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!--  发起任务 end  -->
  </div>
</template>

<script setup>
import { computed, getCurrentInstance, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { debounce } from "lodash";
import { useRouteQuery } from "@vueuse/router";
import { dynamicComponentMap, clientType } from "@/views/client/clientInfo/config";
import { rectificationCount } from "@/apis/rectification";
import { templateTaskList, publishTask } from "@/apis/constructionPlan";
import { clientInfoAndFollow } from "@/apis/clientManager";
import { isQueryDetail } from "@/apis/user";
import { getSubstringBeforeSecondSlash } from "@/utils/url";
import { microAppForceSendData } from "@/microApp";

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const customerId = useRouteQuery("customerId");
const funcTab = useRouteQuery("funcTab");
const backPageUrl = useRouteQuery("backPageUrl");

const activeTabPaneName = ref(clientType.CLIENT_INFO);
const backUrl = ref("");

const setActive = active => {
  activeTabPaneName.value = active.key;
};
funcTab.value && (activeTabPaneName.value = funcTab.value);
backPageUrl.value && (backUrl.value = backPageUrl.value);

const cmpInstance = computed(() => {
  return dynamicComponentMap.has(activeTabPaneName.value) ? dynamicComponentMap.get(activeTabPaneName.value) : "";
});

const params = new URLSearchParams(window.location.search);
const closBrowser = ref("");
closBrowser.value = params.get("closBrowser") || "0";
const handelBack = () => {
  if (closBrowser.value === "1") {
    window.close();
  } else {
    const baseRouter = window.microApp.router.getBaseAppRouter();
    if (backUrl.value) {
      return baseRouter.push({
        name: getSubstringBeforeSecondSlash(backUrl.value),
        path: backUrl.value
      });
    }
    router.replace({ path: "/client-manager" });
  }
};

// const handelBack = () => {
//   const baseRouter = window.microApp.router.getBaseAppRouter();
//   if (backUrl.value) {
//     return baseRouter.push({
//       name: getSubstringBeforeSecondSlash(backUrl.value),
//       path: backUrl.value
//     });
//   }
//   router.replace({ path: "/client-manager" });
// };

const rectificationNum = ref(0);
const getRectificationCount = async () => {
  const { data } = await rectificationCount(customerId.value);
  rectificationNum.value = data.reformCount + data.changeCount || 0;
  if (activeTabPaneName.value !== "rectification") {
    router.replace({
      path: "/client-info",
      query: {
        customerId: route.query.customerId
      }
    });
  }
};

/**
 * 发起任务
 */
const isShowSubmitTask = ref(false);
const submitTaskRules = {
  packageId: [{ required: true, message: "请选择模板", trigger: "blur,change" }]
};
const submitTaskForm = ref({
  packageId: ""
});
const openSubmitTask = () => {
  isShowSubmitTask.value = true;
};
// 搜索模板
const selectTemplateLoading = ref(false);
const templateKeyword = ref("");
const templateList = ref([]);
const getTaskTemplateList = async () => {
  const { data } = await templateTaskList({
    packageName: templateKeyword.value
  });
  templateList.value = data ?? [];
};
const handelSearchTemplate = debounce(getTaskTemplateList, 500);
// 发起任务
const handelSubmitTask = () => {
  proxy.$refs.submitTaskFormRef.validate(async val => {
    if (!val) return proxy.$modal.msgError("请完善信息");
    await publishTask(customerId.value, submitTaskForm.value.packageId);
    proxy.$modal.msgSuccess("任务发起成功");
    handelSubmitTaskClose();
  });
};
const handelSubmitTaskClose = () => {
  isShowSubmitTask.value = false;
  submitTaskForm.value = {
    packageId: ""
  };
};

//获取用户基本信息
const getClientInfoAndFollow = async () => {
  const { data } = await clientInfoAndFollow(customerId.value);
  const result = data ?? {};
  const customerInfo = { customerName: result.customerName, residence: result.residence };
  microAppForceSendData({ customerInfo });
};

/**
 * 是否可查询详情
 */
const isLoading = ref(false);
const isQueryDetailPermission = ref(false);
const getIsQueryDetail = async () => {
  try {
    isLoading.value = true;
    const { data } = await isQueryDetail(customerId.value);
    isQueryDetailPermission.value = data;
    isLoading.value = false;
    if (!data) return;
    getClientInfoAndFollow();
    getRectificationCount();
  } catch (err) {
    isLoading.value = false;
  }
};
getIsQueryDetail();
</script>

<style scoped lang="scss">
@use "clientInfo";
</style>
<style lang="scss">
// 自定义下拉搜索框
@use "@/assets/styles/mixin";

.select-user-popper {
  border: 1px solid #0052d9 !important;
  box-shadow: 0 0 0 2px #d9e1ff !important;
  border-radius: 3px;

  .el-select-dropdown__header {
    padding: 10px 5px 4px 5px !important;
  }

  .el-scrollbar__view > .el-select-dropdown__item {
    @include mixin.flex-align;
    padding-left: 10px;
    padding-right: 10px;
    color: #3d3d3d;
    line-height: 22px;
  }

  .el-popper__arrow::before {
    display: none;
  }
}
</style>
